if( hq == undefined ) {
	var hq = {};
}

hq.ajax = {
	
	$pane : null,
	$breadCrumbs : null,
	$paneUrl : null,
	
	FadeInDt : 100,
	FadeOutDt : 500,

	baseUrl : null,	
	
	init : function( $tgtPane ) {
		console.group( 'ajax::init' );

		if( !$tgtPane || !$tgtPane.length ) {
			throw new Error( "Target pane undefined" );
		}
		this.baseUrl = $j('#ajaxUrl').val();

		this.$pane = $tgtPane;
		this.$breadCrumbs = $j( "#breadcrumbbar" );
		
		var $processElems = $j( this.$pane ).add( this.$breadCrumbs );
		
		this.$pane.bind( 'paneLoaded', toolbox.delegateNPA( this.process, this, $processElems ) );
		
		$j( window ).unload( function() {
			$j('.evtBound').unbind();
		});
		
//		$j('#headLoginBtn').addClass('evtBound').click(toolbox.delegate(this.onSubmit, this));
//		$j('#headCreateAcct').addClass('evtBound').click(toolbox.delegate(this.onLink, this));
		
		//this.process( $j( '#header' ) );
		
		console.group( "evt::paneLoaded" );
		this.$pane.trigger( 'paneLoaded' );
		console.groupEnd();
		
		console.groupEnd();
	},
	
	process : function( $elems ) {
		console.group( 'ajax::process' );
		$elems.find( 'a:not(.ajaxBypass)' ).not( '.disabled' ).addClass( 'evtBound' ).click( toolbox.delegate( this.onLink, this ) );
		
		$elems.find( 'a.disabled' ).addClass( 'evtBound' ).click( toolbox.delegate( this.onDisabledLink, this ) );
//		$elems.find( "input[type='submit']" ).not('.disabled').addClass( 'evtBound' ).click( toolbox.delegate( this.onSubmit, this ) );
		
		var width = this.$pane.find( '#hq_idx_content' ).attr( 'width' );
		if( width && width != this.$pane.width() ) {
			
			console.info( "Pane width change detected: " + width );
			this.$pane.width( width + 'px' );
			
			console.group( "evt::resize" );
			$j( window ).trigger( 'resize' );
			console.groupEnd();
			
		}
		
		var $events = $elems.find( 'input:hidden.ajaxEvent' );
		for( var i=0; $events[i]; i++ ) {
			
			var $event = $j( $events[i] );
			var name = $event.attr( 'name' );
			
			console.group( 'evt::' + name, $event );
			this.$pane.trigger( name, $event );
			console.groupEnd();
				
		}
		
		$j('body').trigger('paneProcessed');
		
		console.groupEnd();
	},
	
	ajaxError : function( request, status, error ) {
		console.group( 'ajax::ajaxError' );
		
		console.error( "AJAX Error" );
		
		this.$pane.find( '.evtBound' ).unbind();
		this.$pane.find( '#hq_idx_content' ).remove();
		
		this.$pane.append( "<div id='hq_idx_content'><span class='errorMsg'>Error</span></div>" );
//		$j( '#loadingMsg' ).fadeOut( this.FadeOutDt );
		hq.loadingMsg.hide();
		
		console.groupEnd();
	},
	
	ajaxSuccess : function( data, status, url, preserveLB ) {
		console.group( 'ajax::ajaxSuccess' );
		var lb = data.match( /<div id='hq_idx_content'[^>]*lightbox[^>]*>/ );
		console.info( !!lb ? "Lightbox page" : "Pane page" );

		// Clear out old content
		if( hq.lightbox && hq.lightbox.isVisible() && !preserveLB) {
			
			hq.lightbox.clear();
			
			if( !lb ) {
				hq.lightbox.hide();
			}
			
		}
		if( !lb ) {
			
			this.$pane.find( '.evtBound' ).unbind();
			this.$breadCrumbs.find( '.evtBound' ).unbind();
			this.$pane.find( '#hq_idx_content' ).remove();
				
		}
		
		// body ID and bread crumbs are only processed for non-lightbox pages
		if( !lb  ) {
			
			var res = data.match( /<body id='([^']*)'/ ); //'
			if( res && res[1] ) {
				$j( 'body' ).attr( 'id', res[1] );
			}

			var start = data.indexOf( "<div id='breadcrumbbar'" );
			var end = data.indexOf( "<!-- END_BREAD_CRUMBS -->" );
			var content = '';
		
			if( start && start >-1 ) {
				start += 24;
				content = data.substring( start, end );
				this.$breadCrumbs.html( content );
			}
			
		}
		
		
		start = data.indexOf( "<div id='hq_idx_content'" );
		end = data.indexOf( "<!-- END CONTENT -->" );
		content = '';
		
		if( start ) {
			content = data.substring( start, end );
		}
		
		
		if( lb ) {
			
			hq.lightbox.update( content );
			hq.lightbox.show();
			this.process( hq.lightbox.$domObj );
			this.$pane.trigger( 'lbLoaded' );
		
		} else {
			
			this.$pane.append( content );
		
			this.$pane[0].scrollTop = 0;
			this.$pane[0].scrollLeft = 0;
		
			console.group( 'evt::paneLoaded' );
			this.$pane.trigger( 'paneLoaded' );
			console.groupEnd();
			
			console.group( 'evt::postPaneLoad' );
			this.$pane.trigger( 'postPaneLoad' );
			
			hq.ajax.paneUrl = url;
				
			console.groupEnd();
			
		}
		
        if(typeof myLightbox == 'object' && myLightbox ){ //If the lightbox object is present then reload all the images... Tony's lightbox-2 mods for pano awareness
            myLightbox.updateImageList();
            $j('.closePano').click(function() { myLightbox.end();});
        }
        

//		$j( '#loadingMsg' ).fadeOut( this.FadeOutDt );
		if(hq.loadingMsg)
			hq.loadingMsg.hide();
		
 
		console.groupEnd();
	},

	loadLink : function( href, preserveLB ) {
		console.group( 'ajax::loadLink' );
	
//		$j( '#loadingMsg' ).fadeIn( this.FadeInDt );
		if(hq.loadingMsg)
			hq.loadingMsg.show();
		
		console.group( 'evt::prePaneLoad' );
		this.$pane.trigger( 'prePaneLoad' );
		console.groupEnd();

		href = this.addRubbish(href);
	
		$j.ajax({
			url : href,
			error : toolbox.delegate( this.ajaxError, this ),
			success : toolbox.delegate( this.ajaxSuccess, this, href, preserveLB )
		});
		
		console.groupEnd();
	},

	addRubbish : function(href) {
		var activeLayer = parseInt($j('.activeLayer').attr('layerId'));

		if(href.indexOf('?') == -1)
                        href += '?ajax=1';
                else
                        href += '&ajax=1';

		if(href.indexOf('activeLayer')==-1 && activeLayer && activeLayer!='NaN') 
			href += '&activeLayer=' + activeLayer;

//		var e = hq.map.getBounds();
		//href += '&minX=' + e.minX + '&maxX=' + e.maxX + '&minY=' + e.minY + '&maxY=' + e.maxY;
		
		return href;
	},
	
	onLink : function( evt ) {
		console.group( 'ajax::onLink' );

		var $target = $j( evt.target );
		
		if( $target.is( 'a' ) == false ) {
			$target = $target.parents( 'a:first' );
			
			if( $target.length == 0 ) {
				console.error( "Failed to find link." );
				console.groupEnd();
				return false;
			}
			
		} else if($target.hasClass('ajaxBypass')) {
			return true;
		}
		
		var target = $target[0];
		
		if( target.hostname !== window.location.host ) {
			console.info( "External Link" );
			console.groupEnd();
			return;
		}
		
		if( parseInt( $j( target ).attr( 'noAjax' ) ) == 1 )  {
			console.info( 'No ajax selected' );
			console.groupEnd();
			return;
		}
		
		console.group( 'evt::prePaneLoad' );
		this.$pane.trigger( 'prePaneLoad' );
		console.groupEnd();
		
		// Avoid the ajax call if we are opening a new window
		if( parseInt( $target.attr( 'newWnd' ) ) == 1 ) {
			var url = $target.attr( 'href' );
			
			window.open( url, '', 'width=800,height=1000,resizable=1,titlebar=1,toolbar=1,menubar=1,status=1,location=1,scrollbars=1' );

		} else {
//			$j( '#loadingMsg' ).fadeIn( this.FadeInDt );

			if(hq.loadingMsg)
				hq.loadingMsg.show();
			
			var url = target.href;
			
			url = this.addRubbish(url);	
				
			$j.ajax({
				url : url,
				error : toolbox.delegate( this.ajaxError, this ),
				success : toolbox.delegate( this.ajaxSuccess, this, target.href )
			});
		}
        
		
		console.groupEnd();
		return false;
	},
	
	onDisabledLink : function( evt ) {
		console.group( 'ajax::onDisabledLink' );
		
		//alert( "Link disabled. Beta Application.\nA work in progress." );
			
		console.groupEnd();
		return false;
	},
	
	onDeadLink : function( evt ) {
		console.group( 'ajax::onDeadLink' );
		console.groupEnd();
		return false;
	},
	
	onSubmit : function( evt ) {
		console.group( 'ajax::onSubmit' );
	
		var $tgt = $j(evt.target);
		var params = toolbox.formVals( $tgt.parents( 'form:first' ) );
		var url = $tgt.parents('form:first').attr('action');
		
		params[ $tgt.attr( 'name' ) ] = $tgt.val();
		
		// Horrible hack to take care of the type vs type[] problem
		if(params['type']) {
			params['type[]'] = params['type'];
			delete params['type'];
		}
		
		console.info( url, params );
		
		var newWnd = parseInt( $tgt.attr( 'newWnd' ) );
		if( newWnd == 1 ) {
			url += '?';
			
			for( var i in params ) {
				if( typeof params[i] == 'object') {
					for( var j=0; j < params[i].length; j++ ) {
						url += i + '=' + params[i][j] + '&';
					}
				} else {
					url += i + '=' + params[i] + '&';
				}
			}
				
			window.open( url, '', 'width=750,height=800,resizable=1,titlebar=1,toolbar=1,menubar=1,status=1,location=1,scrollbars=1' );
			
		} else {	
//			$j( '#loadingMsg' ).fadeIn( this.FadeInDt );
			if(hq.loadingMsg)
				hq.loadingMsg.show();

			var paramStr = toolbox.queryStr( params );
				
		//	var url = $tgt.attr('href');
			
	//		url = this.addRubbish(url);
				
			$j.ajax({
				url : url,
				data : paramStr,
				error : toolbox.delegate( this.ajaxError, this )
		//		success : toolbox.delegate( this.ajaxSuccess, this, url )
			});
		}
		
		console.groupEnd();
		return false;
	}

};

$j(document).ready( toolbox.delegateNPA( hq.ajax.init, hq.ajax, $j( '#contentWrapper' ) ) );

